package nio.GroupChat;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @Author: Dgg
 * @Date: 2021/12/5 22:43
 */
@Slf4j
public class GroupClientThree {

	private final String host = "127.0.0.1";
	private final Integer ip = 6667;

	private Selector selector;
	private SocketChannel socketChannel;
	private String userName;

	public GroupClientThree() {
		try {
			// 得到选择器
			selector = Selector.open();

			socketChannel = SocketChannel.open(new InetSocketAddress(host, ip));
			// 设置非阻塞
			socketChannel.configureBlocking(false);
			// 注册到selector
			socketChannel.register(selector, SelectionKey.OP_READ);
			// 得到userName
			userName = socketChannel.getLocalAddress().toString().substring(1);
			log.info("客户端准备完毕");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendInfo(String info) {
		info = "客户端" + userName;
		try {
			socketChannel.write(ByteBuffer.wrap(info.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void readInfo() {
		try {
			int select = selector.select();
			if (select > 0) {
				Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
				while (iterator.hasNext()) {
					SelectionKey key = iterator.next();
					if (key.isReadable()) {
						// 得到相关通道
						SocketChannel channel = (SocketChannel) key.channel();
						ByteBuffer allocate = ByteBuffer.allocate(1024);
						// 读取
						channel.read(allocate);
						// 把缓冲区数据转成字符串
						String s = new String(allocate.array());
						log.info(s);
					}
					iterator.remove();
				}

			} else {
				log.debug("没有可用的通道...");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// 启动客户端
		GroupClientThree groupClient = new GroupClientThree();
		// 每隔三秒读取 服务器端发送的数据
		new Thread() {
			@Override
			public void run() {
				while (true) {
					groupClient.readInfo();
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		// 客户端发送数据到服务器端
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNextLine()) {
			String s = scanner.nextLine();
			groupClient.sendInfo(s);
		}

	}
}
